"use strict";

const fs = require('fs');
const path = require('path');

var userCache = {}
var tokenCache = {}

module.exports = {
  done(obj) {
    return {
      code: 0,
      success: true,
      timestamp: new Date(),
      result: obj,
    };
  },
  error(code, msg) {
    return {
      code,
      success: false,
      timestamp: new Date(),
      msg,
    };
  },
  list(arr, total) {
    return {
      code: 0,
      success: true,
      timestamp: new Date(),
      result: {
        rows: arr,
        total,
      },
    };
  },
  isJSON(str){
    if (typeof str == 'string'){
      try{
        let obj = JSON.parse(str)
        return true
      }catch(e){
        return false
      }
    }
  },
  loadJson(name) {
    var data;
    try {
      var jsondata = fs.readFileSync(path.join(__dirname,"../mapper/" + name + ".json"));
      data = JSON.parse(jsondata);
    } catch (err) {
      this.logger.error(err.message);
      return undefined;
    }
    return data;
  },
  getUserCache(name){
    if (userCache.hasOwnProperty(name)){
      return userCache[name];
    }else{
      return []
    }
  },
  setUserCache(name,list,auth){
    userCache[name]={role:list,auth,exp:new Date()}
  },
  clearUserCache(){
    for(let key in userCache){
      if (userCache[key].exp>new Date()){
        delete userCache[key];
      }
    }
  },
  removeUserCache(name){
    delete userCache[name]
  },
  getTokenCache(name){
    if (tokenCache.hasOwnProperty(name)){
      return tokenCache[name];
    }else{
      return []
    }
  },
  setTokenCache(name,ip){
    tokenCache[name]={ip,exp:new Date()}
  },
  clearTokenCache(){
    for(let key in userCache){
      if (tokenCache[key].exp>new Date()){
        delete tokenCache[key];
      }
    }
  },
  removeTokenCache(name){
    delete tokenCache[name]
  },
};
